package com.demo;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author wzm
 * @create 2023-09-06 10:06
 * project_name:javaweb2308
 */
//用来打开连接和关闭资源
public class JDBCUtils {
  private static DataSource dataSource = null;

    //类加载是就会执行静态代码块
    static {
        try {
            Properties properties = new Properties();
            properties.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("获得德鲁伊数据库连接池失败");
        }
    }

    //获得数据库连接对象
    public static Connection getConn(){
        try {
            return  dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;//出现异常返回null
    }

    //关闭资源
    public static void closes(Connection connection, PreparedStatement  preparedStatement, ResultSet rs){
        try {

            //关闭执行对象
            if(rs != null) {
                rs.close();
            }

            //关闭执行对象
            if(preparedStatement != null) {
                preparedStatement.close();
            }

            //关闭连接
            if(connection != null) {
                connection.close();
            }


        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

